System verilog constraints
If your simulator supports it, you can use the $countones system function.

class random_error;
    rand bit[31:0] Var1;
    rand int unsigned N;
    constraint random_errorc { $countones(Var1) == N;};
endclass

module top;
    random_error r;
    initial begin
        r = new;
        for (int i = 0; i &lt;= 32; i++) begin
            assert(r.randomize() with {N == i;});
            $display("r.N = %0d, r.Var1 = 32'b%032b", r.N, r.Var1);
        end
    end
endmodule


With Mentor Questa 10.0b, this produces the following output:

# r.N = 0, r.Var1 = 32'b00000000000000000000000000000000
# r.N = 1, r.Var1 = 32'b00000000000000000000000000000010
# r.N = 2, r.Var1 = 32'b00000000000000000000000001000100
# r.N = 3, r.Var1 = 32'b00000000000000000010100000000010
# r.N = 4, r.Var1 = 32'b00000000100100000000000000100010
# r.N = 5, r.Var1 = 32'b00010100000000010000010010000000
# r.N = 6, r.Var1 = 32'b00100010001000000000010000100100
# r.N = 7, r.Var1 = 32'b00001100000111000000100100000000
# r.N = 8, r.Var1 = 32'b01000100101000001010100000000100
# r.N = 9, r.Var1 = 32'b01000000000110100000100100011001
# r.N = 10, r.Var1 = 32'b10110000000000100000100110010101
# r.N = 11, r.Var1 = 32'b01100000010100110000000011010101
# r.N = 12, r.Var1 = 32'b10100110011100000001011001010000
# r.N = 13, r.Var1 = 32'b10001101101100010001010010011000
# r.N = 14, r.Var1 = 32'b01011010010100000100000110101111
# r.N = 15, r.Var1 = 32'b01000101010110110110010100011100
# r.N = 16, r.Var1 = 32'b11100101110110111000100000111000
# r.N = 17, r.Var1 = 32'b11010111101011000100100001110110
# r.N = 18, r.Var1 = 32'b11010101111011001010100101101001
# r.N = 19, r.Var1 = 32'b01100010001011111100101101101111
# r.N = 20, r.Var1 = 32'b10010110010110011111010110011111
# r.N = 21, r.Var1 = 32'b10101111001110111111111100001100
# r.N = 22, r.Var1 = 32'b01110111011101010111001100111111
# r.N = 23, r.Var1 = 32'b01011111010111111001111110011101
# r.N = 24, r.Var1 = 32'b00111110101101111101110111111101
# r.N = 25, r.Var1 = 32'b11111101110010111111011111111100
# r.N = 26, r.Var1 = 32'b11011110111011111111111111110010
# r.N = 27, r.Var1 = 32'b11001001111101111111111111111111
# r.N = 28, r.Var1 = 32'b11111000111111111111111011111111
# r.N = 29, r.Var1 = 32'b11111101111111111111111110101111
# r.N = 30, r.Var1 = 32'b11111111111111111111111110101111
# r.N = 31, r.Var1 = 32'b11111111111011111111111111111111
# r.N = 32, r.Var1 = 32'b11111111111111111111111111111111


Unfortunately, support for this depends on the simulator. I tried with Cadence Incisive 10.0 and it gives a compile error.  If you cannot use $countones, there are other approaches to doing this.

See This link at verificationguild.com for a discussion of this.