Jquery email validation of email and one specific message - ajax

I have a jquery syntax as below
Email: {
required: true,
email: true,
remote: {
url: "emails.php",
type: "post",
},
which validate a field as below;
<td class="field" style="width: 246px">
<input id="Email" name="Email" type="text" value="<?php echo $email; ?>" style="width: 246px">
</td>
<td class="status"></td>
which displays a success/error message in <td class="status">
It validate the data when a valid email ID is entered.
The ajax callback is a simple true/false data.
What i want is, it should also validate when a specific message "NA" is entered in the field. Is this possible??
Here is the complete javascript;
<script id="demo" type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
var validator = $("#signupform").validate({
rules: {
ID: "required",
Name: {
required: true,
minlength: 5,
},
Address: "required",
Dept: "required",
Phone: "required",
College: "required",
LDate: "required",
EDate: "required",
Year: "required",
Privilage: "required",
username: {
required: true,
minlength: 5,
},
Email: {
required: true,
email: true,
remote: {
url: "emails.php",
type: "post",
},
},
LibID: {
required: true,
},
},
messages: {
ID: "Enter ID",
Name: "Enter Name",
Address: "Enter Address",
Phone: "Enter Phone Number",
College: "Specify College",
LDate: "Enter Licenseing Date",
EDate: "Specify License Expiry Date",
Year: "Specify Year",
Dept: "Specify Department",
Privilage: "Specify Privilage",
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters"),
remote: jQuery.format("username not available")
},
Email: {
required: "Enter a valid email address",
minlength: "Enter a valid email address",
remote: jQuery.format("already registered"),
},
LibID: {
required: "Enter a Library ID",
minlength: "Enter a Library ID",
remote: jQuery.format("ID is already in use"),
},
},
errorPlacement: function(error, element) {
error.appendTo( element.parent().next() );
},
success: function(label) {
label.html("OK").addClass("checked");
}
});
$('.username').alphanumeric({nocaps:true}).alphanumeric({ichars:'._'});
});
</script>
Thanks in advance :)
blasteralfred.

I assume you are using the jquery.validation plugin.
If thats the case you can use depends with email rule:
Email: {
required: true,
email: {
depends: function(element){
return element.value != "NA";
}
},
remote: {
url: "emails.php",
type: "post",
},
}

Related

How to send object with an object inside to server Vue.js 3

I need to send object to the server:
{
"id": "null",
"indexNumber": "1454",
"indexYear": "2021",
"firstName": "John",
"lastName": "Doe",
"email": "john#doe.com",
"address": "John Doe Street 1231",
"city": {
"postalCode": 10000,
"name": "New York"
} ,
"currentYearOfStudy": 1
}
when I use to test it from postman everything is fine, but when I try to send object "student" from frontend i got this error message "Cannot read property 'postalCode' of undefined:
Where do I need to define this property, or where to define object city, how to do this?
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
}
Sorry I'm new to vue...
<template>
<div class="form-container m-4 col-6 col-md-8 col-sm-10 mx-auto" display-inline-block>
<h3 v-if="actionType === 'new'">New Student</h3>
<h3 v-else>Edit Student</h3>
<MyInputComponent
name="indexNumber"
label="Index Number"
v-model="indexNumber"
:vcomp="v$.indexNumber"
></MyInputComponent>
<MyInputComponent
name="indexYear"
label="Index Year"
v-model="indexYear"
:vcomp="v$.indexYear" >
</MyInputComponent>
<MyInputComponent
name="firstName"
label="First Name"
v-model="firstName"
:vcomp="v$.firstName"
>
</MyInputComponent>
<MyInputComponent
name="lastName"
label="Last Name"
v-model="lastName"
:vcomp="v$.lastName"
>
</MyInputComponent>
<MyInputComponent
name="email"
label="Email"
v-model="email"
:vcomp="v$.email"
>
</MyInputComponent>
<MyInputComponent
name="address"
label="Address"
v-model="address"
:vcomp="v$.address"
>
</MyInputComponent>
<MyInputComponent
name="postalCode"
label="Postal Code"
v-model="postalCode"
:vcomp="v$.postalCode"
>
</MyInputComponent>
<MyInputComponent
name="name"
label="City Name"
v-model="name"
:vcomp="v$.name"
>
</MyInputComponent>
<MyInputComponent
name="currentYearOfStudy"
label="Curent Year Of Study"
v-model="currentYearOfStudy"
:vcomp="v$.currentYearOfStudy"
>
</MyInputComponent>
<div class="d-flex flex-row-reverse">
<button class="btn btn-outline-primary" #click="saveStudent">Save</button>
</div>
</div>
</template>
<script>
import useValidate from "#vuelidate/core";
import {
required,
minLength,
maxLength,
email,
maxValue,
minValue,
} from "#vuelidate/validators";
import MyInputComponent from "#/components/inputs/MyInputControl.vue";
import StudentService from "#/services/StudentService.js";
import { addMessage } from "#/main.js";
export default {
components: { MyInputComponent },
props: {
studentId: {
type: String,
},
actionType: {
type: String,
},
},
created() {
if (this.studentId) {
StudentService.getStudent(this.studentId).then((response) => {
const student = response.data;
this.indexNumber = student.indexNumber;
this.indexYear = student.indexYear;
this.firstName = student.firstName;
this.lastName = student.lastName;
this.email = student.email;
this.address = student.address;
this.postalCode = student.city.postalCode;
this.name = student.city.name;
this.currentYearOfStudy = student.currentYearOfStudy;
});
}
},
data() {
return {
v$: useValidate(),
id:null,
indexNumber: "",
indexYear: "",
firstName: "",
lastName: "",
email: "",
address: "",
postalCode: "",
name: "",
currentYearOfStudy: null,
randomNumber:''
};
},
validations() {
return {
indexNumber: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
indexYear: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
firstName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
lastName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
email: {
required,
email,
},
address: {
required,
minLength: minLength(3),
},
postalCode:{
required,
minValue: minValue(9999),
maxValue: maxValue(100000),
},
name:{
required,
minLength: minLength(3),
maxLength: maxLength(30)
},
currentYearOfStudy: {
required,
minValue: minValue(1),
maxValue: maxValue(5),
},
};
},
methods: {
saveStudent() {
if (this.actionType && this.actionType === "new") {
this.inserStudent();
} else {
this.updateStudent();
}
},
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
},
updateStudent() {
StudentService.editStudent({
id: this.studentId,
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy,
})
.then((response) => {
console.log("Student inserted" + response);
addMessage({
message: "Student updated",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Update was not successful:" + error,
type: "danger",
title: "Update student",
});
});
},
},
};
</script>
You've postalCode and name are defined in data property without nesting them, so you could nest them to a city field when you want to send the request :
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
city:{
postalCode: this.postalCode,
name: this.name,
},
currentYearOfStudy: this.currentYearOfStudy
})

Laravel - Change error message for Authenticates user

I changed login condition as per my requirement in AuthenticatesUsers
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'), ['is_approved' => 1]);
}
But for Not Approved error message is These credentials do not match our records.
How to change this message?
did you mean validations?? you can change it using the novalidation. just insert that at the end of the form. if it does not work, you can use a js.
here's a sample js:
var $ = jQuery;
$(document).ready(function($) {
$("form[name='Cust_Form']").validate({
errorElement: 'div',
rules: {
postal_code: {
number: true,
minlength: 4,
maxlength: 4,
required: true
},
email: {
email: true
},
unit: {
number: true
},
building: {
number: true
},
contact_2: {
number: true,
minlength: 11,
maxlength: 11
},
contact_1: {
number: true,
minlength: 11,
maxlength: 11
}
},
// Specify validation error messages
messages: {
postal_code: {
minlength: "Your postal code must be at least 4 characters long",
number: "Please enter a valid postal code",
maxlength: "Your postal code must be at least 4 characters long",
required: "Required field"
},
email: {
email: "Please enter a valid email address"
},
unit: {
number: "Please enter a valid unit number"
},
building: {
number: "Please enter a valid building/house number"
},
contact_1: {
minlength: "Your contact number must be at least 11 characters long",
number: "Please enter a valid contact number",
maxlength: "Your contact number must be at least 11 characters long"
},
contact_2: {
minlength: "Your contact number must be at least 11 characters long",
number: "Please enter a valid fax/phone number",
maxlength: "Your contact number must be at least 11 characters long"
},
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});

Conditional and custom validation on Add / Edit form fields when using Kendo grid custom popup editor template

I am using a custom template for kendo grid popup Add / Edit form. Here is my working DEMO
I want to implement conditional validation on form fields such as if any value is entered for Address (not left empty) then the fields City and Postal Code should become required, otherwise they can be empty. Also I want to ise a custom validation rule for PostCode so that its length should always be equal to 4 else it should show a custom error message as "Postcode must be four digits"
I have referred these links:
Validation rules in datasource.model
Custom validation rules and error messages
but I can't figure out how can I implement validations in my datasource model?
Here is my code:
HTML:
<h3>I want to implement conditional validation on Add/Edit form such as if any value is entered for Address then the fields City and Postal Code should become required</h3>
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address"/></label>
</p>
<p>
<label>City: <input name="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode"/></label>
</p>
</script>
JS:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
If i were to do that, i would do these approach where
I will create a custom validator
Override the edit(grid) function place the validator there
Override the save(grid) function use validator.validate() before saving
Here is an example in dojo
basically this is the grid code:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
save: function(e) {
if(!validator.data("kendoValidator").validate()){
e.preventDefault();
}
},
edit: function(){
validator = $("#test-form").kendoValidator({
validateOnBlur: false,
rules: {
matches: function(input) {
var requiredIfNotNull = input.data('test');
// if the `data-test attribute was found`
if (requiredIfNotNull) {
// get the input requiredIfNotNull
var isFilled = $(requiredIfNotNull);
// trim the values and check them
if ( $.trim(isFilled.val()) !== "" ) {
if($.trim(input.val()) !== ""){
// the fields match
return true;
}else{
return false;
}
}
// don't perform any match validation on the input since the requiredIf
return true;
}
// don't perform any match validation on the input
return true;
}
},
messages: {
email: "That does not appear to be a valid email address",
matches: function(input) {
return input.data("testMsg");
}
}
});
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
ps: i used to many if statement, you could simplify it i think
Here is the DEMO how I implemented it:
HTML:
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<div id="myForm">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address" id="address"/></label>
</p>
<p>
<label>City: <input name="city" id="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode" id="postcode"/></label>
<!--<span class="k-invalid-msg" data-for="postcode"></span>-->
</p>
</div>
</script>
JS:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ field: "address" },
{ field: "city" },
{ field: "postcode" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30, address:'Addr', city:"city", postcode: '1234' },
{ id: 2, name: "John Doe", age: 33, address:'Addr11', city:"city11", postcode: '4321' }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }],
save: function(e) {//alert('save clicked');
if(!validator.validate()) {
e.preventDefault();
}
},
edit: function(e){
//alert('edit clicked');
validator = $("#myForm").kendoValidator({
messages: {
postcode: "Please enter a four digit Postal Code"
},
rules: {
postcode: function(input) {
//console.log(input);
if (input.is("[name='address']"))
{
if (input.val() != '')
{
$('#city, #postcode').attr('required', 'required');
//return false;
}
else
{
$('#city, #postcode').removeAttr("required");
}
}
else if (input.is("[name='postcode']")) {
if ($('#address').val() != '' && input.val().length != 4)
return false;
}
return true;
}
},
}).data("kendoValidator");
},
});

When I add remote to Jquery Validate form submits when invalid

When I add remote to the jquery validate my form submits even if there are errors, when I remove remote it works properly and you can't submit the form and unless you have filled in all fields? Any ideas? code is below
<script>
$(document).ready(function () {
$("#SignUp").validate({
onsubmit: true,
onkeyup: function(element) { $(element).valid(); },
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
password: true
},
confirm_password: {
equalTo: "#password",
required: true
},
company: {
nls:true,
required: true
},
telephone: {
required: true,
phoneUK: true
},
email2: {
email: true
},
website: {
url: true
},
address1: {
nls:true
},
address2: {
nls:true
},
town: {
nls:true
},
postcode: {
postcodeUK:true
},
country: {
selectcountry:true
},
terms:{
required:true
},
answer:{
remote: "Captcha/check-captcha.php",
type: "POST",
data: {
captcha: function() {
return $("#answer").val();
}
}
}
},
messages:{
email:
{
required: "Please Enter an Email Address"
},
password:
{
required: "Please Enter a Password"
},
confirm_password:
{
required: "Please Confirm Your Password"
},
company:
{
required: "Please Enter Your Company/Climbing Gym Name"
},
telephone:
{
required: "Please Enter a Telephone Number"
},
terms:
{
required: "Please Agree Our Terms and Conditions"
},
answer:{
remote: "You Have Entered The Captcha Correctly When This Message Disappears"
}
}
});
$.validator.addMethod("password", function (value, element) {
return this.optional(element) || /^[A-Za-z0-9!##$%^&*()_]{6,16}$/i.test(value);
}, "Passwords are 6-16 characters");
$.validator.addMethod("nls", function(value, element)
{
return this.optional(element) || /^[a-zA-Z0-9\s.\-_']+$/i.test(value);
}, "Please Only Enter Alpha Numeric Characters and Spaces");
jQuery.validator.addMethod('selectcountry', function (value) {
return (value != 'Nothing');
}, "Please Select a Country");
$.validator.addMethod("url", function(value, element)
{
return this.optional(element) || /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i.test(value);
}, "Please Enter A Valid Website URL");
});
</script>
PHP is below:
<?php
session_start();
if(strtolower($_REQUEST['answer']) == $_SESSION['captcha']){
echo 'true';die;
}else{
echo 'false';die;
}
?>
The validation still works onkeyup etc with and without remote but just not on submit?
The remote rule syntax is slightly off in your case
answer: {
required: true,
remote: {
url: "Captcha/check-captcha.php",
type: "POST",
data: {
captcha: function () {
return $("#answer").val();
}
}
}
}

kendoAutoComplete shows [object object] when clicked on template or item

This code return the result below in snaps.
How to populate text field with FirstName and LastName when click on template instead of [object object] ?
function forAutoComplete(FieldName){
var autoCompleteUsers = $("#employees").kendoAutoComplete({
minLength: 1,
dataTextField: FieldName,
template: '<div style="border-bottom: 1px solid DARKGRAY; padding:10px 0; clear:both;">' +
'<img style="float:left; margin-right:20px;" width=\"127\" height=\"127\" src=\"<?php echo base_url() ?>/user_uploads/employee_images/${data.Photo}\" alt=\"${data.Photo}\"/>'+
'<div style="display: inline-block;"><p>${ data.FileNo}</p>' +
'<h3>${ data.FirstName } ${ data.LastName }</h3></div>'+
'<div style="clear: both; "></div></div>',
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: "<?php echo base_url() ?>index.php/hr_management/manage_hr/search_employee/",
data: function (arg){
return {FieldName : autoCompleteUsers.data("kendoAutoComplete").value()};
}
}
}
},
height: 300,
change: onChangeAutoComplete
});
}
The problem is likely to be related with the value that you set for dataTextField.
Doing some-sort-of-reverse-engineering, I guess that the JSON data that you return is something like:
[
{data: { FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" } },
{data: { FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" } },
{data: { FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" } }
]
If so, you should be defining it as data.FirstName.
If you are defining it as:
[
{ FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" },
{ FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" },
{ FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" }
]
Then it should be just FirstName.
Example of the first approach in here while second in here
If you define dataTextField: "data", and use the first approach for your JSON then you get the [object Object]. See it here

Resources