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!
Related
In my view i have
#using (Html.BeginForm(null,null,FormMethod.Post, new {onsubmit="return
validateForm(this);", name = "frm", id = "frm" }))
and in my JS file i have this code
function validateForm(form) {
alert("Called")
var x = form[model.username].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
When i use just an alert in the JS, it works. However when i pass in the form, even if the username is blank, the rest of the data is submitted. Am using ASP MVC 5
any ideas please?
Let's assume that model.username contains "johndoe123". That value is then used, meaning that in fact you are requesting form["johndoe123"].value which I think is pretty unlikely to return a value. It may even produce an error, especially if either model or model.username are undefined.
You probably meant to request a form field that has name="username" or something like that, so I'll give an example on how to do that:
var form = document.getElementById("theForm");
console.log(form);
console.log(form["username"]);
console.log(form["username"].value);
<form id="theForm">
<input type="text" name="username" value="something">
</form>
I was working on a very basic HTML form and was asked to add email validation. The form is sent via an AJAX post, so I can't use the standard HTML validation with a submit button:
<form>
<input type="email" id="email">
<input type="submit" value="Submit">
</form>
I could just add some regex to the JS, but this made me wonder, is it possible interact with the browsers built-in validation from JS?
E.g. A built-in function or property that could be give the inputs current state in terms of validation (valid/invalid)
Something like:
var valid = document.getElementById("email").isValid();
I think you can using the checkValidity method on each element:
var email = document.getElementById('email');
var isValid = email.checkValidity();
if (isValid) {
// Submit form
}
You can also use the validity property on an element to check which validation constraints failed:
var validity = email.validity;
if (validity.valueMissing) {
return 'Please enter your email';
}
Yes you can, using Constraint validation API methods.
You can find out the details in here:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Data_form_validation#Validating_forms_using_JavaScript
You are thinking on something like this:
JS
<script>
function checkEmail() {
var x = document.getElementById("email");
if(x.value.includes("#")){
// do something or just continue
}else{alert("Not valid email!")
}
}
</script>
I have two page - 1. Index.html
2. Main.html
I want to sent a data from index to main. Which i can do like this:
<form action="Main.html" method="POST">
<input type="text" name="q">
</form>
I want to display the data sent from Index.html on Main.html
I know two methods of doing it -
1. using method="GET" in the form tag and get the data from the src(link).
2. Using side languages like php.
I dont want to use the first method to do this thing.
Please someone give me the codes of php for doing this.
It would be more help if you can tell any other way of doing this
Change your Main.html to Main.php
To get data in the Main.php with post method is just: $_POST['q'].
If you want to display your input text, just echo it: echo $_POST['q'].
Or you can save it into a variable too: $var = $_POST['q'].
Or if you don't want to use PHP, you can save input's value into a cookie and get that cookie's value in the Main.html with just JavaScript.
// function to get cookie || Parameter is your required cookie's name
function getcookie(cookiename)
{
var name = cookiename+"=";
var cookiearray = document.cookie.split(';');
for(var i=0; i<cookiearray.length; i++)
{
var c = cookiearray[i].trim();
if(c.indexOf(name) === 0)
{
return c.substring(name.length, c.length);
}
}
return "";
}
You have another option, if you don't want to use server side language...
you can use JavaScript, or it's library like jQuery to do that.
One HTML file:
<form method="POST">
<input type="text" name="q">
</form>
Other HTML file:
<div id="here"></div>
The jQuery file:
var result = $("input[name=q]").val();
$("#here").text(result);
if you want to use it, read more about JavaScript and jQuery... (Google)
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 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.