EndsWith in Javascript for Validation Form - javascript

I have a question. How to do a validation form in javascript that the condition is "Must be ended with 'City'"?

This is simple example i have to taken to make you understand about the endsWith() method.
function myFunction2() {
var str = "This is City but I am not there";
var n = str.endsWith("City");
document.getElementById("result").innerHTML = n;
}
function myFunction() {
var str = "Welcome to my City";
var n = str.endsWith("City");
document.getElementById("result").innerHTML = n;
}
function validate(){
var txtdata = document.getElementById("city").value;
var txtdata = txtdata.endsWith("City");
if(txtdata){
document.getElementById("result2").innerHTML = "City Found at end";
}else{
document.getElementById("result2").innerHTML = "Must be ended with City";
}
}
<button onclick="myFunction()">Check its working with City</button>
<button onclick="myFunction2()">Check its working without City</button>
<div id="result"></div>
<!-- Validate in form data -->
<form>
<input type="text" id="city" name="city"/>
<input type="button" onclick="validate()" value="Submit"/>
</form>
<div id="result2"></div>
In the similar way you have to take input from form store it in a variable do validation.

Related

Why is this simple Javascript refactor not working?

A simple question about a form submit in HTML.
Why does this work:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
output.innerText = inputStuff.value;
return false;
}
But this doesn't:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
var out = output.innerText;
var into = inputStuff.value;
out = into;
return false;
}
Here's the HTML:
<h1>Put your input in here</h1>
<form onsubmit="return useMethod(this)" action="">
<input type="text" id="inputBox">
<input type="submit" value="Submit">
</form>
<h2>Output:</h2>
<p id="outputBox">Starter text</p>
Many thanks in advance for any help,
R
out = into; will simply assign the value of into (string) to out (string), whereas output.innerText = inputStuff.value; will invoke an implicit setter that will change the DOM value as well.

.test() method in javascript is not working properly

In this code, the variable value of "ans" is always false whether I have entered value according to pattern or not. I cannot understand the reason.
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
Try this
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
<script>
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
</script>
You should move all your code into a defined function validate()
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
You used function named validate in the submit button event, but did not define it. After defining the validate function, everything works fine.
function validate() {
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>

Problems with an IF statement in JavaScript

When I type in an ID number for the game, I always gets the 3rd statement of my if else expression. Where am I going wrong?!!
<html>
<body>
<p>Type in the ID and hit search:</p>
<button onclick="myFunction()">Search</button>
<p id="demo"></p>
<form>
<input id="textbox" type="text" />
</form>
<script>
var textboxValue = document.getElementById("textbox").value;
function myFunction() {
var message;
if (textboxValue == 1) {
message = "Fantasy World";
} else if (textboxValue == 2) {
message = "Sir Wags A Lot";
} else {
message = "Take a Path";
}
document.getElementById("demo").innerHTML = message;
}
</script>
</body>
</html>
The problem is you always test the same, initial, value of the input.
Change
var textboxValue = document.getElementById("textbox").value;
function myFunction() {
to
function myFunction() {
var textboxValue = document.getElementById("textbox").value;
This way the value will be read each time the function is called.
Put this statement:
var textboxValue = document.getElementById("textbox").value;
Inside the function.

How to Pass the Email Id value after checking Captcha in Asp.Net Mvc4?

I am new one to Asp.Net Mvc4 with Entity Framework. Now i am doing Captcha verification for Forgot Password. As my code, I it is passing the Email id value to Controller when i am clicking submit button even the Captcha code is Invalid. I want to pass the Email id value to controller if the Captcha code is correct otherwise it should show the validation error and New captcha should get reloaded. Please help me to fix it. Thanks in advance.
This is my Java Script code for generation and validating the captcha:
var captchastring = '';
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 7;
captchastring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum, rnum + 1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
function validation() {
var text2 = document.getElementById("txtcode").value;
if (text2 == captchastring) {
var email = document.getElementById("UserEmail").value;
x = document.getElementById("demo");
// Find the element
x.innerHTML = "valid";
x.style.color = "#ff0000";
}
else {
x = document.getElementById("demo"); // Find the element
x.innerHTML = "Invalid Captcha. Try again";
x.style.color = "#ff0000";
}
}
</script>
This is my body of my cshtml code:
<div class="col-md-5">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h5 class="nomargin">Forgot Password</h5>
#Html.TextBoxFor(u => u.UserEmail, new { #class = "form-control", placeholder = "Email" })
<br />
<div id="captcha">
<div id="captcha_gen">
<label id="randomfield">
</label>
</div>
<button type="button" onclick="getCaptcha();" style="border: 0; background: transparent;float:right; position:relative";>
<img src="../../Content/FSLBootstrapUI/images/playback_reload.png" width="25" height="25" alt="submit" />
</button>
</div>
<input type="text" id="txtcode" class="form-control" placeholder="Enter code here" />
<button class="btn btn-success btn-block" value="submit" onclick="validation()">Reset</button> <p id="demo"> </p>
}
</div>
What is happening currently? I mean, how is the application behaving?
EDIT:
You can try server side validation for example if you have a field to validate you can add a validation tag there.For example:
<input type="text" name="SampleTextBox" id="SampleTextBoxId"/>
#Html.ValidationMessage("SampleTextBox", "*")
Then you go to the controller and add this kind of code:
if (!string.IsNullOrEmpty(SampleTextBox))
{
//Your Code.
}
else
{
ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not be empty.");
}
Use Model.IsValid as your condition to write your main code.
Model.IsValid becomes False if ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not be empty."); is executed.
This is a way to add validations. You can check for your valid/invalid captcha in your controller itself and throw error.
For Example:
if (IsValidCaptcha(enteredCaptcha))
{
//Code
}
else
{
ViewData.ModelState.AddModelError("captchaId", "Enter valid captcha");
}
Lastly, add a validation summary to your page
#Html.ValidationSummary("Error Messages")

Validate that Name field contains text only

I want that Name field should contain text only.
<html>
<head></head>
<body>
<form name="form1">
Name <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Can anyone tell me how can I do so using either HTML or Javascript.
Use this regex in your Javascript: /^[a-z]+$/i
WORKING DEMO
Javascript:
var submit = document.getElementById("submit");
submit.addEventListener("click", checkInput, false);
function checkInput(e){
e.preventDefault();
var pattern = /^[a-z]+$/i;
alert(pattern.test(document.getElementById('text').value));
}
You can test whether there's "anything left" after removing alpha characters.
<html>
<body>
<form name="form1" onsubmit="return checkform();">
Name<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
<script>
function checkform(){
var fname=document.getElementById('fname').value;
if (fname.replace(/\w/g,'')!=''||fname==''){
alert('invalid firstname!');
return false;
}
return true;
}
</script>
</body>
</html>
try this:
<script type="text/javascript">
function validate(){
var allowedChars="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n=form1.fname.value;
for(var i=0;i<n.length;i++){
if(allowedChars.indexOf(n.charAt(i))==-1){
return false; // contains other char
}
}
return true; //valid name
}
Try regular expressions like
var match_text = /[a-zA-Z]/;
try this var regx = /^[A-Za-z][-a-zA-Z ]+$/;
function validate_form();
{
var regx = /^[A-Za-z][-a-zA-Z ]+$/;
var fname = document.getElementById('fname').value;
if(fname=="")
{
alert("Name is Blank");
return false;
}
else if(!regx.test(fname))
{
alert("name must contains character only");
return false;
}
else
{
return true;
}
}
Pattern checking of the textbox must be done with Javascript or Jquery like in other answers BUT if you want to use HTML5, you can directly write :
<input type="text" name="fname" id="fname" pattern="[A-Za-z]+" />
(See 'pattern' attribute in HTML5 if you're interested).
You can call this function to validate input field containing only text--
function validate()
{
str = document.form1.fname.value;
var patt = new RegExp("^[a-zA-Z ]*$");
var res = patt.test(str);
if(!res)
{
alert("do not match!");
return false;
}
}

Categories

Resources