Angular 4 enable HTML5 validation

前端 未结 2 794
[愿得一人]
[愿得一人] 2020-12-09 15:51

I want to use HTML5 validation in Angular 4 rather than their form\'s based validation/reactive validation. I want to keep the validation running in the browser.

I

相关标签:
2条回答
  • 2020-12-09 16:13

    Angular4 automatically adds a novalidate attribute to forms.

    To override this, you can add the ngNativeValidate directive to the form.

    <form ngNativeValidate>
    <h2>Phone Number Validation</h2>
    <label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br />
    <input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>
    
    <input type="submit" value="Submit">
    
    </form>
    

    Unfortunately I do not see this reflected in the docs yet, but found it by looking at the source code: https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_no_validate_directive.ts

    It appears also adding ngNoForm to the form has the same effect as ngNativeValidate depending on your use-cases for needing to declare something as not a form for whatever reason.

    Hope this helps.

    0 讨论(0)
  • 2020-12-09 16:23

    use ngNoForm or ngNativeValidate in your form

    <form ngNoForm/ngNativeValidate>
    ...
    </form>
    
    0 讨论(0)
提交回复
热议问题