How can I simplify form validation?

前端 未结 11 1491
[愿得一人]
[愿得一人] 2020-12-14 00:57

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 01:56

    I know the question is old but I want to share with the world my awesome new angular directive, I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... Enough said, let's give some examples:

    
    
    
    
    
    
    
    

    So I can define whatever amount of validation rules which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add :)

    No more clustered Form with 10 lines of code for 1 input when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And don't worry about the form not becoming invalid, I took care of that as well, it's all handled the good way.

    Take a look at my Github project Angular-Validation and spread the word =)

    EDIT
    To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's busy typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
    You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:

    
    


    EDIT #2
    Also added input match confirmation validation (ex.: password confirmation), here is a sample code

    
    
    
    
    
    

    EDIT #3
    Refactored the directive so that the requirement of having a to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.

    DEMO
    Added a live demo on Plunker

提交回复
热议问题