Getting "Object is possibly 'null'. TS2531" on a form input field - javascript

I'm trying to build a simple form to capture email and password for a new user signing up on Firebase, I'm using React with Typescript and I'm getting the error "Object is possibly 'null'. TS2531" on the following section of the code:
<form onSubmit={(event) => { this.handleSignUp({event, email: this._email.current.value, password: this._password.current.value})}}>
In particular it's the this._email.current.value and this._password.current.value that are throwing this error.
I've dug around about both the error code and type scripting and it's something to do with the "strictNullChecks" on the typescript, but I don't really want to turn that option off, and I don't think I have enough skill or understanding of coding to know how to get around this. Even though I do understand that a form can be submitted with empty values, I am checking later with the firebase auth to make sure that there are strings with more than 4 characters.
Below is the code for the whole react component.
interface IHandleSubmitNewUserFunc {
event: any,
email: any,
password: any
}
class NewUserSignup extends React.Component {
constructor(props: any) {
super(props);
this.handleSignUp = this.handleSignUp.bind(this);
}
handleSignUp(input: IHandleSubmitNewUserFunc) {
input.event.preventDefault();
const { email, password } = input;
if (email.length < 4 && email != null) {
alert('Please enter an email address.');
return;
}
if (password.length < 4 && password != null) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
private _email = React.createRef<HTMLInputElement>();
private _password = React.createRef<HTMLInputElement>();
render() {
return <div>
<div className="signup-modal-container">
<div className="identity-panel">
<img src={logo}></img>
<form onSubmit={(event) => { this.handleSignUp({event, email: this._email.current.value, password: this._password.current.value})}}>
<div className="form-flex-container">
<div className="signup-item">
<h2>
Sign Up
</h2>
<label htmlFor="email" id="email">
Email:
</label>
</div>
<div className="signup-item">
<div className="input-container">
<input type="text" name="email" id="email" ref={this._email}/>
</div>
</div>
<div className="signup-item">
<label htmlFor="password">
Password:
</label>
</div>
<div className="signup-item">
<div className="input-container">
<input type="password" name="password" id="password" ref={this._password}/>
</div>
</div>
<div className="signup-item">
<button type="submit">
Sign Up
</button>
</div>
</div>
</form>
</div>
</div>
<p>
NewUserSignup is showing
</p>
</div>
}
}
export default NewUserSignup;
I'm not really sure what code I'd need to not throw this error, any advice is aprpeciated.

Pretty much as it says. The references are null by default, there's no guarantee that current is assigned by the time you access them (as far as the code knows).
You have 2 options:
Add a truthy check before access this._email.current and this._password.current.
const eCurrent = this._email.current;
const pCurrent = this._password.current;
if (!eCurrent || !pCurrent) {
// This will probably never happen, to respond to events these will be hooked up.
return;
}
Use the non-null assertion since you know it's a safe operation: this._email.current!.value.
// Assert that current won't be null.
const emailValue = this._email.current!.value;
const passwordValue = this._password.current!.value;

Related

email validation in angular

i am trying to add validation to email.
Structure : using reactive form, get email and check if already exist using filter javascript.
component.ts:
isUniqueEmail(): ValidatorFn {
return (control: AbstractControl): any | null => {
if(control.value.email != null){
this.httpService
.getDataFromServer("api/employees?company_branch=" +this.user.branch_id)
.subscribe((resp) => {
var data = resp.data.employee;
const found = data.filter(v => v.email == control.value.email);
if(found.length !== 0){
console.log("found one");
return {exist: true}
}
});
}
}
}
if email already exist console.log print found and every thing work fine.
declaration of form control:
this.employeeForm = new FormGroup({
email: new FormControl(null,
[
Validators.required,
Validators.pattern("^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$"),
ValidatorsSettings.notOnlyWhitespace,
]),
),{validators: this.isUniqueEmail()}}
in html :
<div class="row">
<div class="from-group">
<label for="Email"> Email </label>
<mat-divider></mat-divider>
<input
type="text"
id="Email"
class="form-control"
formControlName="email"
/>
<div *ngIf="employeeForm.get('email').invalid && (employeeForm.get('email').touched || employeeForm.get('email').dirty)" class="help-block">
<div *ngIf="employeeForm.get('email').errors.required || employeeForm.get('email').errors.notOnlyWhitespace" class="help-block">
Email is required
</div>
<div *ngIf="employeeForm.get('email').errors.pattern" class="help-block">
Email must be a valid email address format
</div>
<mat-error *ngIf="employeeForm.errors?.exist" class="help-block"
>Email Already Exist</mat-error>
</div>
</div>
</div>
error not showing ! what i do wrong ?
Since the validator is using a service to request the response it should be an asyncValidator. The code could end up as:
isUniqueEmail(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors>=> {
if(control.value.email != null){
return this.httpService
.getDataFromServer("api/employees?company_branch="+this.user.branch_id).pipe(
.map((resp) => {
var data = resp.data.employee;
const found = data.filter(v => v.email == control.value.email);
if(found.length !== 0){
console.log("found one");
return {exist: true}
}
});
}
else return null;
}
}

Cannot POST / login.html

I'm having trouble sending data to the server using a form. I already made a register form that works just fine, and for the most part my client side javascript for the login form is very similar to the javascript for the register form, and I just can't figure out why it won't work. It just gives me "Cannot POST /login.html"
Here's the login form html:
<div class="loginTitle">
<h1>Login</h1>
</div>
<div class="loginFormLayout">
<form method=post id="loginForm">
<div class="loginFormText">
<label for="username">Username</label>
</div>
<div class="loginFormEntry">
<input type="text" placeholder="Enter Username" name="loginUsername" required>
</div>
<div class="loginFormText">
<label for="password">Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Enter Password" name=loginPassword required>
</div>
<button type="submit" class="loginButton">Log In</button>
</form>
</div>
And here's the client side javascript:
//Login as an existing user
const login = document.getElementsByClassName('loginButton');
const loginForm = document.getElementById('loginForm');
const loginURL = 'http://localhost:3000/loginUser';
loginForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(loginForm);
let username = formData.get('loginUsername');
let password = formData.get('loginPassword');
loginForm.reset();
let user = { //Create a user object that will be sent to the backend and compared to the user database
username,
password
};
fetch(loginURL, { //Send the user object to the backend in JSON format to be checked against the database
method: 'POST',
body: JSON.stringify(user),
headers: {
'content-type': 'application/json'
}
})});
And the server side javascript for now, console logs are just to see if the info is getting up to the server
app.post('/loginUser', (req, res) => {
console.log(req.body.username);
console.log(req.body.password);
});
EDIT: I've also decided to post the info for my register form, which DOES work and uses similar logic to the login form. Maybe I'm missing something that isn't in the login logic
Register form html:
<div class="loginMenu">
<div class="loginTitle">
<h1>Register</h1>
</div>
<div id="registerWarning"></div>
<div class="loginFormLayout">
<form method="post" id="registerForm">
<div class="loginFormText">
<label for="username" id="newUsername">Username</label>
</div>
<div class="loginFormEntry">
<input type="text" placeholder="Create Username" name="username" required>
</div>
<div class="loginFormText">
<label for="password" id="newPassword">Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Create Password" name=password required>
</div>
<div class="loginFormText">
<label for="confirmPassword">Confirm Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Confirm Password" name="confirmPassword" required>
</div>
<button type="submit" class="registerButton">Register</button>
</form>
</div>
</div>
Register form client side javascript:
//Register a new user
const register = document.getElementsByClassName('registerButton');
const registerForm = document.getElementById('registerForm');
const registerURL = 'http://localhost:3000/createNewUser';
//When the user presses the register button, get the info from the form
registerForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(registerForm);
let newUsername = formData.get('username');
let newPassword = formData.get('password');
let confirmPassword = formData.get('confirmPassword')
registerForm.reset();
//Make sure new password and confirm password are equal
if (newPassword == confirmPassword) {
if (newUsername != "" && newPassword != ""){ //Make sure user enters something for both fields
let newUser = { //Create an object to send to the back end
newUsername,
newPassword
};
fetch(registerURL, { //Send the newUser object to the backend in JSON format to be added to the database
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'content-type': 'application/json'
}
});
}
}
else { //If newPassword and confirmPassword are not equal, ask the user to enter them correctly
const registerWarning = document.getElementById('registerWarning');
registerWarning.innerText = 'Password and Confirm Password do not match';
registerWarning.style.padding = "10px";
registerWarning.style.background = 'red';
};
});
Register form server-side javascript:
app.post('/createNewUser', (req, res) => {
let newUsername = req.body.newUsername;
let newPassword = req.body.newPassword;
let newUserData = 'INSERT INTO users (username, password) VALUES (?, ?)';//Use the question marks as placeholders
//Use bcrypt to hash the password before putting it in the database
bcrypt.hash(newPassword, saltRounds, function(err, hash) {
db.query(newUserData, [newUsername, hash], function(err, result) {
if (err) throw err;
console.log('New user registered');
});
});
});
I figured it out, thanks to #Rocky Sims for the help.
Basically, the register form doesn't exist on the login html page, which was throwing an error up about how that doesn't exist before it could even get to the login code. So I just had to make seperate register.js and login.js files, as the issue was due to them being in the same file.
Try wrapping your form method (post) in quotes ('') like so <form method='post' id="loginForm">
Also the value for the name attribute for your password input should by in quotes. Like so <input type="password" placeholder="Enter Password" name='password' required>
I think the problem is that you haven't told the server what to send back to the client when the POST /loginUser endpoint gets called. Try adding res.sendStatus(200); at the end of your POST /loginUser handler function (so right after console.log(req.body.password);).

Vue remove invalid input message

When an input field requires more info, the browser shows a message in a bubble about why the input is invalid. I would like to prevent the default for this in vue but I'm not sure how. Below is how I would do it in JavaScript but in Vue, there may be a way to do #invalid like how I know you can do #submit on a form as an eventListener. I'm also wondering if extra prevention is needed to prevent this in ios or android.
HTML
<form>
<input type="text" required>
<input type="submit">
</form>
JS
document.querySelector( "input" ).addEventListener( "invalid",
function( event ) {
event.preventDefault();
});
https://codepen.io/albert-anthony4962/pen/BajORVZ
If you want to completely disable validation, you can add novalidate="true" to your form element.
I suspect that you might only want to do that on the initial page load. If so, could you update your section and hopefully and add an example? I can update my answer after that 😀
A pattern I have (idea from Vuetify) is pretty easy:
new Vue({
el: "#app",
data: {
isFormValid: null,
form: {
input_1: {
text: null,
rules: ['required', 'min3'],
validateText: null
},
input_2: {
text: null,
rules: ['required'],
validateText: null
}
},
rules: {
required: v => !!v && !![...v].length || 'This field is required.',
min3: v => !!v && !!([...v].length > 2) || 'This field must be at least 3 characters long.'
}
},
methods: {
validateForm() {
const validated = []
for (let key in this.form) {
const v = this.form[key].rules.map(e => {
return this.rules[e](this.form[key].text)
})
if (v.some(e => e !== true)) {
this.form[key].validateText = v.filter(e => e !== true)[0]
validated.push(false)
} else {
this.form[key].validateText = "This field is valid."
validated.push(true)
}
}
return validated.every(e => e === true)
},
submitForm() {
if (this.validateForm()) {
// submit logic
this.isFormValid = "Yes, it's valid."
} else {
// not valid logic:
this.isFormValid = "No, it's not valid."
}
},
resetValidation() {
const form = JSON.parse(JSON.stringify(this.form))
for (let key in form) {
form[key].validateText = null
}
this.isFormValid = null
this.form = form
},
resetForm() {
const form = JSON.parse(JSON.stringify(this.form))
for (let key in form) {
form[key].validateText = null
form[key].text = null
}
this.isFormValid = null
this.form = form
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form ref="formRef">
<label for="input_1">
Input 1:
<input
id="input_1"
type="text"
v-model="form.input_1.text"
/>
</label>
<div>This field will validate if NOT EMPTY AND HAS AT LEAST 3 CHARS</div>
<div>{{ form.input_1.validateText || ' ' }}</div>
<br />
<label for="input_2">
Input 2:
<input
id="input_2"
type="text"
v-model="form.input_2.text"
/>
</label>
<div>This field will validate if NOT EMPTY</div>
<div>{{ form.input_2.validateText || ' ' }}</div>
<br />
<button type="submit" #click.prevent="submitForm">
SUBMIT
</button>
<div>Is the form valid? {{ isFormValid }}</div>
</form>
<button #click="resetValidation">RESET VALIDATION</button><br />
<button #click="resetForm">RESET FORM</button>
</div>
This way you don't have to put up with the HTML5 "bubbles", but can still validate your form - in any way you need. You can compose any validation scheme you want by using functions that go over your input text. You could even come up with regexp validation, pattern validation (like phone numbers), etc. It's not the greatest solution, but quite "pluggable".
This is also supposed to be cross-platform (if you use Vue).

When input field is prepopulated the field is invalid

I have a form where I enter an email and confirm email and then continue to the next page and all is well. The validation works fine when the page initially loads and it's the user's first time, so the input field is not prepopulated from cookie data. However, when the user returns, the input field data is prepopulated from cookie data and that is fine but the submit button is still disabled even though the prepopulated text is valid format. I inspected the elements and it seems to think the field is ng-invalid even though it's valid format.
I noticed when I go to one of the fields and backspace to remove the last character and reinsert the same character as before for email and do the same for the next field, the form is valid again. Even though, it's the same text as before.
I'm wondering why validation fails when the form first loads with prepopulated data?
Here's my code:
export class EmailComponent implements OnInit {
public user : User;
Form : FormGroup;
displayErrors : boolean;
ngOnInit() {
// initialize model here
this.user = {
Email: '',
confirmEmail: ''
}
}
constructor(fb: FormBuilder, private cookieService: CookieService, private cryptoService: CryptoService) {
var encryptedEmail = this.cookieService.get(AppCookie.EmailAddress);
var Cookie = null;
if(encryptedEmail != null && encryptedEmail != 'undefined')
Cookie = this.cryptoService.Decrypt(encryptedEmail);
if(Cookie == null) {
this.Form = fb.group({
email: ['', [Validators.required, Validators.pattern(EMAIL_REGEXP)]],
confirmEmail: ['', [Validators.required, Validators.pattern(EMAIL_REGEXP)]]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
else {
this.Form = fb.group({
email: [Cookie, [Validators.required, Validators.pattern(EMAIL_REGEXP)]],
confirmEmail: [Cookie, [Validators.required, Validators.pattern(EMAIL_REGEXP)]]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
}
save(model: User, isValid: boolean)
{
model.Email = this.Form.get('email').value;
var encrypted = this.cryptoService.Encrypt(model.Email);
this.cookieService.put(AppCookie.EmailAddress, encrypted);
}
matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailKey];
let confirmEmail = group.controls[confirmEmailKey];
if (email.value !== confirmEmail.value) {
return {
mismatch: true
};
}
};
}
}
and here's my view:
<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)">
<div class="login-wrapper">
<div class="login-page">
<section class="login-form form-group">
<p>
<input id="email"
[class.email-address-entry]="!displayErrors"
[class.email-address-entry-text]="!displayErrors && this.Form.get('email').value !='' "
type="email"
placeholder="name#domain.com" formControlName="email" />
</p>
<p class="login-form__msg">Reenter your email to confirm</p>
<input id="reenteremail"
[class.email-address-entry]="!displayErrors"
[class.entry-border-invalid]="displayErrors && !Form.valid && Form.errors?.mismatch"
[class.email-address-entry-text]="!displayErrors && this.Form.get('email').value !='' "
(blur)="displayErrors=true"
type="email" placeholder="name#domain.com"
formControlName="confirmEmail"/>
<p class="error-msg" *ngIf="displayErrors && !Form.valid && Form.errors?.mismatch">The email you entered does not match.</p>
</section>
<p class="login-confirm">
<span>
<button type="submit" [disabled]="!Form.valid" (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN">Confirm</button>
</span>
</p>
</div>
</div>
</form>
EDIT: It's similar to this issue as well:
Angular 2 - Form is invalid when browser autofill
I tried adding this:
ngAfterViewChecked() {
if (Cookie) {
// enable to button here.
var element = <HTMLInputElement> document.getElementById("confirmBtn");
element.disabled = false;
}
But it won't work because fields are still invalid. I need a way to manually set re-validation or change ng-invalid to ng-valid.
If you keep a reference to the form instance (either by using reactive forms or by accessing it using #ViewChild) you should be able to write the following in ngAfterViewInit():
for (var i in this.form.controls) {
this.form.controls[i].updateValueAndValidity();
}
Or perhaps marking the fields as touched will be better in your case:
for (var i in this.form.controls) {
this.form.controls[i].markAsTouched();
}

How to submit form only if condition is true

I'm trying to implement authentification system with express + node js. So far it's been good, but now I see that even when I refresh the page, the form submits to the server. This is how my code looks like:
Client side:
submit(e) {
let data = this.state; /// object with user's informations
e.preventDefault()
validate.form(this.state.username, this.state.email, this.state.password, this.state.confirm) // this returns true if everything is fine or returns the error string!
}
render() {
return (<div>
<form action="/login" onSubmit = {this.submit} method="post">
<p>Username:</p>
<input type="text" onChange = {this.getData} name="username" value = {this.state.username} />
<p>Email</p>
<input type="text" onChange={this.getData} name = "email" value = {this.state.email} />
<p>Password</p>
<input type="text" onChange={this.getData} name = "password" value = {this.state.password} />
<p>Confirm Password</p>
<input type="text" onChange={this.getData} name = "confirm" value = {this.state.confirm} />
<br/> <br/>
<input type="Submit" value='Submit' /> ///this is not working!
</form>
</div>)
}
Server side:
app.post('/login',(req, res) => {
console.log(req.body)
res.sendFile(__dirname + '/src/index.html')
db.query('INSERT INTO users SET ?', req.body, (err, res) => console.log("done!"))
})
TL;DR I'm looking to submit the form only if validate.form(username, email, password, confirm) returns true. I'm using bodyParser as module to parse the json!
Assuming that form.validate() is synchronous, you should call preventDefault only if form.validate() returns the error string.
submitForm(e) { // avoid to use 'submit' as method name
let data = this.state; /// object with user's informations
let formValid = validate.form(this.state.username, this.state.email, this.state.password, this.state.confirm);
if(formValid !== true) {
e.preventDefault()
}
// else, if formValid is true, the default behaviour will be executed.
}

Categories

Resources