How to give custom validation error messages for HTML validations?

前端 未结 2 418
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 10:59

When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for

相关标签:
2条回答
  • 2021-01-29 11:18

    Try this one, its better and tested: HTML:

    <form id="myform">
    <input id="email" 
           oninvalid="InvalidMsg(this);" 
           oninput="InvalidMsg(this);"
           name="email"  
           type="email" 
           required="required" />
    <input type="submit" />
    

    JAVASCRIPT:

    function InvalidMsg(textbox) {
    if (textbox.value === '') {
        textbox.setCustomValidity('Required email address');
    } else if (textbox.validity.typeMismatch){
        textbox.setCustomValidity('please enter a valid email address');
    } else {
       textbox.setCustomValidity('');
    }
    
    return true;
    

    }

    Demo:

    http://jsfiddle.net/patelriki13/Sqq8e/

    0 讨论(0)
  • 2021-01-29 11:20

    It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate

    Custom Message - jQuery Form Validation - abValidate.js

    ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
    

    Use this library by adding these CDNs

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <!-- abValidate Library -->
    <script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
    <link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
    

    Initialize the library

    $(document).ready(function () {
        //.ab-form is your form class
        $(".ab-form").abValidate();
    });
    

    There you go, now you can use your custom validation using jQuery abValidate library

    <form class="ab-form" action="your_action_url">
    
       <!-- Input and error message should be in a div class -->
       <div class="my-form-group">
            <input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
            <div class="error"></div>
        </div><br>
    
        <div class="my-form-group">
            <input type="submit" name="submit" value="Submit">
        </div>
    
    </form>
    
    0 讨论(0)
提交回复
热议问题