简体   繁体   中英

How to validate input field on change and show the message to the user?

I have input field where user should enter System ID. After user enters System ID validation should be triggered. If System ID is valid, ajax request is sent to the server. If System ID is invalid, user should see the message. I use JQuery with Bootstrap 3.3.7 for this project. Here is example of my code:

 $('#system_id').on('change', getInfo); function getInfo(e) { var fldObj = $(this), fldVal = fldObj.val(); if (fldVal.length > 0 && fldVal.length <= 8 && Number.isInteger(Number(fldObj.val()))) { //Send Ajax Request console.log('Send request for System ID: ' + fldVal); } else { // Show message to the user. if (fldVal.length === 0) { fldObj.parent().removeClass('has-error has-feedback'); $('#symbol-error').remove(); } else { console.log('Invalid System ID'); fldObj.parent().addClass('has-error has-feedback').append('<span id="symbol-error" class="glyphicon glyphicon-remove form-control-feedback"></span>'); } } } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div class="container"> <div class="form-group"> <label class="control-label" for="system_id">System ID:</label> <input class="form-control" type="text" name="system_id" id="system_id" value="" placeholder="Enter System ID"> </div> </div> 

So far my logic works fine, I'm checking if user input value is integer and if it's in range between 1 and 8. I would like to display the message inside of the input field with alerts (bootstrap 3) if possible. If anyone know how to do this or if there is a better method for this please let me know. Thank you.

You can add to the script after the line console.log('Invalid System ID'):

  fldObj.parent().addClass('has-error has-feedback');
  $('#system_id').val('Invalid System ID');

The first line will color the input.
The second line will insert your message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM