最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate form input before submiting - Stack Overflow

programmeradmin2浏览0评论

I have a form with two input : one for Hostname another for ip address. how can i validate these two fields before submit the form and if they are not match with their pattern show an error.for example :Enter correct hostname. here is patterns:

Host : ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$

Ip : ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

Here is my snippet but it is not working :

$('#hosti').focusout(function() {
    $('#hosti').filter(function() {
        var hosti = $('#hosti').val();
        var hostiback = $('#hosti');
        var hostiReg = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
        if (!hostiReg.test(hosti)) {
            $('#hosti').css('boxShadow', '0px 0px 2px 1px #E25249');
        } else {
	   $('#hosti').css('boxShadow', '0px 0px 0px 0px #E25249');
        }
    })
});
<script src=".0.1/jquery.min.js"></script>
<form>
  HOST :
<input type="text"  placeholder="Host" id="hosti" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/"/>
  
  IP ADDRESS :
  <input type="text"  placeholder="IP Address" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/"/>

  
  <button type="submit">Submit</button>
</form>

I have a form with two input : one for Hostname another for ip address. how can i validate these two fields before submit the form and if they are not match with their pattern show an error.for example :Enter correct hostname. here is patterns:

Host : ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$

Ip : ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

Here is my snippet but it is not working :

$('#hosti').focusout(function() {
    $('#hosti').filter(function() {
        var hosti = $('#hosti').val();
        var hostiback = $('#hosti');
        var hostiReg = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
        if (!hostiReg.test(hosti)) {
            $('#hosti').css('boxShadow', '0px 0px 2px 1px #E25249');
        } else {
	   $('#hosti').css('boxShadow', '0px 0px 0px 0px #E25249');
        }
    })
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form>
  HOST :
<input type="text"  placeholder="Host" id="hosti" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/"/>
  
  IP ADDRESS :
  <input type="text"  placeholder="IP Address" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/"/>

  
  <button type="submit">Submit</button>
</form>

Share Improve this question edited Jan 16, 2017 at 7:26 inaz asked Dec 14, 2016 at 12:10 inazinaz 1,7855 gold badges22 silver badges43 bronze badges 4
  • Use required attribute – A. Wolff Commented Dec 14, 2016 at 12:12
  • i want to validate form with their pattern if i use required attribute. it is just check the field that empty or not. – inaz Commented Dec 14, 2016 at 12:29
  • The pattern regex should not contain / delimiters. To display an error message, an input must have a title attribute. – Wiktor Stribiżew Commented Dec 14, 2016 at 12:30
  • See this JSfiddle. – Wiktor Stribiżew Commented Dec 14, 2016 at 12:38
Add a ment  | 

5 Answers 5

Reset to default 3

Dunno what the focusout function is about... Why would you need that?

The pattern attribute handles what you need. You have however used the same pattern for both fields. And as Wiktor pointed out - you don't use the / for patterns. I've also added required.

This HTML should be all you need to make it work:

<form>
HOST :
<input type="text"  placeholder="Host" id="hosti" pattern="^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$" required/>

IP ADDRESS :
<input type="text"  placeholder="IP Address" pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" required/>


  <button type="submit">Submit</button>
</form>

It appears as if SO's snippets don't support forms, but you can see it here at JSFiddle.

First of all, pattern regexps cannot have regex delimiters, the / must be removed. Also, these patterns are anchored by default (i.e. wrapped within ^(?: and )$), the ^ and $ are not necessary in the patterns you have.

To show an error message on submit, you need to add title attributes to the input nodes.

Also, you may add CSS styles to invalid and valid properties of the elements being validated.

See a demo below and a JSFiddle:

.to_validate:valid {
  color: black;
  border: 5px solid #dadadada; // dadada .glowing-border: http://stackoverflow./questions/5670879/css-html-create-a-glowing-border-around-an-input-field
  border-radius: 7px;
}
.to_validate:invalid {
  color: navy;
  outline: none; // .glowing-border:focus 
  border-color: #ff1050;
  box-shadow: 0 0 10px #ff0000;//#9ecaed
}
<form>
  HOST :
<input type="text"  placeholder="Host" class="to_validate" id="hosti" pattern="(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])" title="Wrong Host"/>
  IP ADDRESS :
  <input type="text" class="to_validate"  placeholder="IP Address" pattern="(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" title="Wrong IP"/>
  <button type="submit">Submit</button>
</form>

If you want to fail a match once the whole HostName field input is equal to a number +.+ number +.+ number +.+ number pattern, add a (?!\d+(?:\.\d+){3}$) negative lookahead at the start:

pattern="(?!\d+(?:\.\d+){3}$)(([a-zA-Z\d]|[a-zA-Z\d][a-zA-Z\d-]*[a-zA-Z\d])\.)*([A-Za-z\d]|[A-Za-z\d][A-Za-z\d-]*[A-Za-z\d])"

See a JSFiddle here.

This lookahead matches 1 or more digits, and then 3 sequences of a dot and 1+ digits, and then the end of string (here, we need to define the end of string pattern explicitly as it is not at the end of the pattern).

You can use validation engine plugin (https://github./posabsolute/jQuery-Validation-Engine) and drop inside your patterns

Or just use input mask for users clarity with your patterns (https://github./RobinHerbots/Inputmask)

Last is less safe but anyway backend validation is inevitable

Check this out try put some value in host input and see

$(document).ready(function(){
  $( "input[name='host']")
   .focusout(function() {
     var pat_h  = $( "input[name='host']").attr("pattern");
     var val = $( "input[name='host']").val();
     var reg = new RegExp("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
     if(reg.test(val)){
      alert("match")
     }
     else{
       alert("not match");
     }

   });
 });
<script src="https://ajax.googleapis./ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form>
  HOST : 
  <input  type="text"  placeholder="Host" id="hosti" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/" name="host"/>
  
  IP ADDRESS :
  <input name="ip" type="text"  placeholder="IP Address" pattern="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/"/>

  
  <button type="submit">Submit</button>
</form>

Basically what you're trying to achieve is an intermediate state between the button click event and form submission. What you can do is remove the type="submit" attribute from the button and capture the button click event, where you can validate your inputs and then submit the form. Something like this:

$("#submit_button").on("click", function() {
  /* DO ALL YOUR REQUIRED INPUT VALIDATIONS AND DISPLAY ERRORS */
  $("#my_form").submit();
}
发布评论

评论列表(0)

  1. 暂无评论