-1

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 each validations such as min, max, type and require. For Example:

The field is required, The value does not match

Refer the tradition HTML Code:

<input type="text" required>

I want something like this:

<input type="text" validation="required|my_message,min:5|my_message">
Priyanka
  • 169
  • 3
  • 10
  • 1
    This is not possible in standard HTML. If you want this you'd need to use a third party library. If you're happy using jQuery, I'd suggest jQuery validate – Rory McCrossan Dec 21 '18 at 08:49
  • The most you can do without JS is to use the :valid selector in CSS and some creativity to show/hide different elements. You can't get the level of detail you want without JS though. – Chris Rollins Dec 21 '18 at 09:09

2 Answers2

1

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>
Googlian
  • 6,077
  • 3
  • 38
  • 44
0

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/

Akash Gupta
  • 34
  • 10