I have an html file which contains a form. There is lots of text typed input control need customer to input information. How do I check whether the customer's input is correct?
For example, I want to check if the username only contains digits, letters and '_'.
Please help me.
I'd appreciate if somebody can provide me a demo.
Thanks in advance!
Here’s one possible approach, for a simple task like the one given as example:
<script>
function check(elem) {
if(elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
return true;
} else {
alert(elem.getAttribute('data-msg'));
return false;
}
}
</script>
<input name=username pattern=[a-zA-z0-9_]{1,9} onblur=check(this)
data-msg="The user name may only contain letters A–Z, digits, and underlines and must be 1 to 9 characters.">
The idea here is to start with the HTML5 pattern attribute, specifying the allowed pattern of data as a regular expression. It already works on several modern browsers and does no harm when it doesn’t. Then you add an event attribute, which causes a JavaScript-driven check to be made, using the regular expression taken from the same attribute (with a prefix and postfix character added so that the check is made on the input item as a whole).
You may wish to display the error message in some less disruptive manner than via alert()
<input type="text" id="username" />
<span id="invalidMessage" style="display:none; color:Red"><img src="../../Images/error.gif" alt="OK" />invalidEmail。</span>
<script type="text/javascript">
$(document).ready(function() {
$('#username').blur(function() {
$('#invalidMessage').hide();
if ($('#username').val() != "") {
var email = /_*\w+(-?\w+)*#_*\w+(-?\w+)*(._*\w+(-?\w+)*)*.\w*/;
if (!email.test($('#username').val())) {
$('#invalidMessage').show();
}
}
});
});
</script>
There is a demo,hope can help you.
I would use something like this on the client side;
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}
//-->
</script>
Then, i would use more robust error checking on the server side to ensure you have valid data. If you can catch bad data at the client, its a plus, as it avoids the hit on the server, but the validation really belongs on the data on the server side, as its more secure and can be reused by other forms.
Related
I have list of codes almost 1000 codes like "PB5KE13" and i have to check these codes through input field. If the input value have a code then show Ok message. Is there anything I can get through Javascript. I don't want these in PHP or Database. I can't use these. Only HTML and Javascript.
I know the if else condition. but with this large list may be i can't use.
<form method="POST" action="" onsubmit="return checkForm(this);">
<input type="text" name="inputfield" value="">
<input type="submit" value="validate">
</form>
<script>
function checkForm(form)
{
// validation fails if the input is blank
if(form.inputfield.value == "") {
alert("Error: Input is empty!");
form.inputfield.focus();
return false;
}
}
</script>
If there is are codes to be validated, it is recommended to validate with server side script like PHP as Javascript is client side and anyone can see your code and it would not make much sense to ask for a code. But in case I misunderstood your requirement, Here is Javascript code:
let inputField = document.getElementById('#code');
let codes = ['PB5KE10','PB5KE11','PB5KE12','PB5KE13','PB5KE14']; // Can add More
function validate(val,code){
result = false;
for(let i=0;i<code.length;i++){
if(val==code[i]){
result = true;
break;
}
}
return result;
}
console.log(validate(input.value,codes)); //true if value is in array else false
Assuming you have all the codes in an array in Javascript, the only thing you need to do is use the includes() method on an array:
myKeys.includes(myInputValue);
Check out the W3Schools link for details:
https://www.w3schools.com/jsref/jsref_includes_array.asp
Hope it helps!
i am developing application using Code-igniter.
I want to validate Text Box Using J Query Or JavaScript That only allowed to input following URL when user submit form.
http://
https://
ftp://
ftps://
file://
market://
linkedin://
fb://
geo:
maps://
Is there any way to do this ?
function is_url(str)
{
regexp = /^(?:(?:https?|ftps?|file?|market?|linkedin?|fb?|maps?):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (regexp.test(str))
{
return true;
}
else
{
return false;
}
}
Try using this regex in a function that checks validity of your input.
/^(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//g
But do the reverse logic:
if it matches then display error mesage and clear input.
If it not matches then your URL is fine
If you wanna prevent URLs anywhere in your input, remove the leading ^ in regex to match even if URL is not start of the string.
like: /(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//gm
Here is a crud version of entire solution:
fiddlejs
Main thing is URL validation:
$("#urlInput").focusout(function (){
var inputElement = $("#urlInput");
var regexp = /(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//gm;
if (regexp.test(inputElement.val())){
inputElement.val("");
alert("This is nto a valid URL")
}
});
It bound to the
<input id="urlInput" type="url">
You might wanna rework the error reporting in a more user friendly manner but that's another story.
I have already built a form validator in JS, a portion of which is displayed below. I just need help in displaying an error and scrolling to the field.
Okay, so each <input> will have attributes specifying the validation they need, eg:
<input data-mandatory="yes" data-validation="phone" data-max-digits="10">
There attributes are parsed at the time of form submission, and if I come across an errornous field I need to scroll to that field and display an error in English (multilingual not needed).
var $form = $('#main-form');
$form.submit(function(event) {
event.preventDefault();
// per field
$form.find("input,textarea").each(function(f, field){
// read metadata
var type = $(field).attr("type");
var mandatory = $(field).data("mandatory");
var maxDigits = $(field).data("max-digits")) || 1000;
var validation = $(field).data("validation");
// read value
var value = $(field).value();
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
// HOW DO I SHOW AN ERROR AT THE CURRENT FIELD?
// and how do I scroll to it?
}
}
});
});
Edit: I've got a non-trivial amount of code in node.js (5K LOC) which I'm porting to the client side, which is required by my organization. That code is not displayed above.
Edit: I've looked online for an hour but the jQuery form validator libraries that I've seen do not function the way I need. I already have form sanitation & validation code (which supports various data types like phone number, ZIP code, etc) in Node.js which I'm just porting to the client side.
First of all i would recommend to use some free validation plugin. But, if you want for some reason to write it your self, than the answer to your question is:
First you need to have the error message hidden somewhere in your markup. There is a number of ways to do this. Most common solution would be something like that:
<div>
<input type="text" required />
<p class="error">Error</p>
</div>
Than you need to display it, in your example it could be done like this:
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
//show error
$(this).parent().find('.error').show();
//scroll
$('html, body').animate({
scrollTop: $(this).offset().top
}, 2000);
return; // stop validation(becouse you dont want to scroll more times)
}
}
You will need to figure out some more things (like hide all the errors before validating again), but this should answer your question.
I know there are many methods of validating forms on both client and server side but I was wondering what was the best practice?
Currently, I have Javascript functions validating form input fields 'on the fly' with onkeyup/onblur functions like so:
(Partial code:)
<p class="form-registerUserName">
<div class="upperLabel">
<label for="registerUserName">User Name</label>
<span class="required">*</span>
</div>
<input
id="registerUserName"
name="registerUserName"
type="text"
size="24"
maxlength="24"
value="<?php echo $_SESSION['registerUserName'];?>"
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
<label for="registerUserName" class="hint" id="registerUserNameHint"></label>
</p>
With Javascript functions like:
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
} else {
document.getElementById("registerUserName").setAttribute("style","border-color: rgb(221,221,221) rgb(241,241,241) rgb(241,241,241) rgb(221,221,221);");
document.getElementById('registerUserNameHint').innerHTML = '';
}
} //validateName()
..So that the input box turns red and shows a hint on the side of the box if it does not validate.
So my question was - What is the best way to prevent the form from submission to my (Mysqli) database when the user hits submit?
(and second question..) Do I run an additional php server-side script after client-side validation has cleared?
Some ways I imagined to accomplish this is by having my Javascript functions set a Session variable that indicates an error condition, and not allow a submit if there was.
I am not certain how to do that, or how I set up my 'submit' to not work unless the error condition was cleared.
Would appreciate any help on that.
Then do I re-validate the same data (in the same manner) with php again, after a successful client-side validation before inserting into my database?
Thanks in advance.
First off, always do server-side validation!
Second, HTML5 form validation is well supported.
Examples: http://html5pattern.com/
You can then use CSS for validation styling.
Structure your validation with this logic:
if validateName() {
document.getElementById("myForm").submit();
}
// if returns true (passed validation) then submit
//validate on click of submit button or on submit
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
**return false;**
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
**return false;**
........ so forth
else {
return true;
}
I have a textbox where the user is required to insert a valid email address.
When the user submits a valid email address a loading graphic appears while the data is posted back.
The code below works fine for showing the loading graphic but it does not check that the email address is valid first. Can anyone help out?
$('#btnEmail1Submit').live ("click", function() {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
});
I am thinking that I need to put an if statement around the function that is run on click - so something like:
$('#btnEmail1Submit').live ("click", function() {
if(emailvalid == true) {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
}
});
I am using asp.net email validation - it looks something like this:
<asp:RegularExpressionValidator Display="Dynamic" ValidationGroup="PrimarySubmit" ID="RegularExpressionValidator1" runat="server" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail1" ErrorMessage="Invalid email address - " />
You will need to use a regex to test the email address for validity:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
That came from this question, so see that thread for more info.
You need to call that function with the email address provided by the user, so I'm assuming something like:
var email = $("#emailInput").val();
if(isValidEmailAddress(email)) {
//Do stuff
}
You should check the email validity using a regexp
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
$('#btnEmail1Submit').live ("click", function() {
if(!email.match(re)) {
alert('invalid email');
return false;
}
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /> </div>').appendTo(".emailEditContainer");
});
The regexp comes from Validate email address in JavaScript?
Email validation has been discussed many, many times on SO, and elsewhere. In short it's hard (impossible) to do perfectly and is a trade off between maximising coverage of valid formats and minimising false positives. In fact all i do to validate email addresses is a basic sanity check. In pseudocode:
if (address.contains("#")) {
.. // then ok
}
Anything else is basically futile. Even if you spend ages constructing some insanely complex regex to comply with RFC822 to get most valid addresses (there are real addresses that don't comply with the RFC) - how do you know this inbox actually exists?
you can check this
function myClick() {
Page_ClientValidate();
if (Page_IsValid) {
return true;
}
else {
return false;
}
}
if you are using regularexpression validator then this can be used....
If you need to execute the aps validator to validate the email address, which seems to be pertinant to your question, then you need to call the generated javascript that does this before you make the call - so call:
if(Page_ClientValidate)
do your other stuff
However, this will run all of the page validation, not just the email.
If you need to only run the one validation call for this, you can look at the generted javascript on your page, and find where it does the call for your email validation, and call that. However, I would not recommend that, as it may change when the page is regenerated.
See CodeProject